package cn.itcast.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.common.BaseAction;


@SuppressWarnings("serial")
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User>{
    
	@Action(value="user_login",results={@Result(name="login",type="redirect",location="login.html"),
	@Result(name="success",type="redirect",location="index.html")})
	public String login(){
		System.out.println("用户名是"+model.getUsername());
		System.out.println("密码是"+model.getPassword());
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken  token = new UsernamePasswordToken(model.getUsername(),model.getPassword());
		try {
			//登录成功  存入session
			subject.login(token);		
			return SUCCESS;
		} catch (Exception e) {
			//登录失败返回登录页面
//			了解 Shiro 执行流程， 应用程序 --- Subject --- SecurityManager --- Realm 安全数据
			e.printStackTrace();
		     return LOGIN;
		}
	}
	
	
	@Action(value="user_loginout",results={@Result(name="success",type="redirect",location="login.html")})
	public String loginout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}
	
	@Autowired
	private UserService userService;
	
	//查询用户数据列表
	@Action(value="user_list",results={@Result(name="success",type="json")})
	public String list(){
		List<User>list = userService.findAll();
		System.out.println("查询所有的数据列表");
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	//属性驱动
	private String [] roleIds;

	public String[] getRoleIds() {
		return roleIds;
	}


	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	
	
	
	@Action(value="user_save",results={@Result(name="success",type="redirect",
			location="pages/system/userlist.html")})
	public String save(){
		userService.save(model,roleIds);
		return SUCCESS;
	}
}
